package com.ymatou.iapi.trading.useranalysis.testcase;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymatou.iapi.trading.useranalysis.parameter.GetBuyerFirstOrderInfoBean;
import com.ymatou.iapi.trading.useranalysis.parameter.resp.BuyerFirstOrderInfo;
import com.ymatou.iapi.trading.useranalysis.parameter.resp.GetBuyerFirstOrderInfoResp;
import com.ymatou.iapi.trading.useranalysis.service.GetBuyerFirstOrderInfoCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceOrderCallService;
import com.ymttest.database.mongo.YmtBuyerOrdersWrapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.ECode;

/**
 * 获取买家在指定卖家下的订单统计信息接口
 */
@TestSuite
public class Ts_GetBuyerFirstOrderInfo {
	private static GetBuyerFirstOrderInfoBean req;
	private static GetBuyerFirstOrderInfoCall call;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("获取买家在指定卖家下的订单统计信息接口");
	}

	@Before
	public void caseUp() {
		req = new GetBuyerFirstOrderInfoBean();
		call = new GetBuyerFirstOrderInfoCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(call.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void getDataFromMongo(GetBuyerFirstOrderInfoResp resp) throws Exception {
		Map<Integer, BuyerFirstOrderInfo> firstOrder = new HashMap<Integer, BuyerFirstOrderInfo>();
		for (Integer userId : req.getBuyerIds()) {
			BuyerFirstOrderInfo orderInfo = getBuyerOrder(userId);
			firstOrder.put(userId, orderInfo);
		}
		resp.setFirstOrderInfos(firstOrder);
	}

	@SuppressWarnings("rawtypes")
	public BuyerFirstOrderInfo getBuyerOrder(int userId) throws Exception {
		BuyerFirstOrderInfo orderInfo = new BuyerFirstOrderInfo();
		YmtBuyerOrdersWrapper wapper = new YmtBuyerOrdersWrapper();
		
		List<Map> list = wapper.getByUserId(userId);
		
		if (DataUtil.isNullOrEmpty(list)) {
			orderInfo.setNewCustomer(true);
		} else {
			
			if (list.get(0).get("PaidTime") == null)
				orderInfo.setNewCustomer(true);
			else
				orderInfo.setNewCustomer(false);
		
			Object pdTm = list.get(0).get("PaidTime");
			
			if (pdTm != null) {
				
				Date date = YMTDateUtil.getDate(String.valueOf(pdTm), YMTDateUtil.YMDGMT, Locale.US);
				
				orderInfo.setFirstOrderTime(date);
			}
		}
		return orderInfo;
	}

	public void constructExpectedResult(GetBuyerFirstOrderInfoResp resp) throws Exception {
		getDataFromMongo(resp);
	}

	private void verify() throws Exception {
		DataUtil.verify(ECode.SUCCESS, call.getCode(), "验证code");

		GetBuyerFirstOrderInfoResp expectResult = new GetBuyerFirstOrderInfoResp();
		constructExpectedResult(expectResult);
		GetBuyerFirstOrderInfoResp actualResult = call
				.getBuyerFirstOrderInfoResp();
		Map<Integer, BuyerFirstOrderInfo> expect = expectResult
				.getFirstOrderInfos();
		Map<Integer, BuyerFirstOrderInfo> actual = actualResult
				.getFirstOrderInfos();
		if (expect == null || expect.size() == 0) {
			DataUtil.verify(true, expect == null || actual.size() == 0,
					"验证FirstOrderInfos == null || FirstOrderInfos.size() == 0");
		} else {
			DataUtil.verify(expect.size(), actual.size(),
					"验证FirstOrderInfos.size()");
			boolean sameSize = expect.size() == actual.size();
			if (sameSize) {
				Iterator<Integer> it = expect.keySet().iterator();
				while (it.hasNext()) {
					Integer expUserId = it.next();
					DataUtil.verify(true, actual.containsKey(expUserId),
							"验证FirstOrderInfos中存在用户id:" + expUserId);
					BuyerFirstOrderInfo expOrderInfo = expect.get(expUserId);
					BuyerFirstOrderInfo actOrderInfo = actual.get(expUserId);
					if (expOrderInfo == null) {
						DataUtil.verify(null, actOrderInfo,
								String.format("验证用户id为%d的首单信息为空", expUserId));
					} else {
						DataUtil.verifyObject(expOrderInfo, actOrderInfo,
								String.format("用户id为%d的首单信息", expUserId));
					}
				}
			}
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_001() {
		Logger.start(true, "获取已有多笔付款订单的老用户买家的首单信息--获取成功,非首单用户");
		try {
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));

			TradingPlaceOrderCallService.placeOrderWithUserId(userId);
			List<Integer> buyerIds = new ArrayList<Integer>();
			buyerIds.add(userId);
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_002() {
		Logger.start(true, "获取无订单的新用户的首单信息--获取成功,属于首单用户");
		try {
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();
			List<Integer> buyerIds = new ArrayList<Integer>();
			buyerIds.add(userId);
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_003() {
		Logger.start(true, "获取有订单但无付款订单的新用户的首单信息--获取成功,属于首单用户");
		try {
			OrderCallService orderCallService = new OrderCallService();

			int userId = orderCallService.createNewUser();
			TradingPlaceOrderCallService.placeOrderWithUserId(userId);

			List<Integer> buyerIds = new ArrayList<Integer>();
			buyerIds.add(userId);
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_004() {
		Logger.start(true, "获取有且有付款订单的新用户的首单信息--获取成功,非首单用户");
		try {
			OrderCallService orderCallService = new OrderCallService();

			int userId = orderCallService.createNewUser();
			TradingServiceResp placeOrder = TradingPlaceOrderCallService.placeOrderWithUserId(userId);
			long tradingId = placeOrder.getTradingId();
			BigDecimal totalPrice = placeOrder.getPayableAmount();
			long orderId = placeOrder.getOrderList().get(0).getOrderId();
			
			TradingCallService.payOrder(userId, totalPrice, tradingId, false, 2);
			TradingSyncService.getSyncResult(orderId);

			List<Integer> buyerIds = new ArrayList<Integer>();
			buyerIds.add(userId);
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_005() {
		Logger.start(true, "获取有且都是未付款状态订单的新用户的首单信息--获取成功,属于首单用户");
		try {
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();
			
			for (int i = 0; i < 5; i++) {
				TradingPlaceOrderCallService.placeOrderWithUserId(userId);
			}

			List<Integer> buyerIds = new ArrayList<Integer>();
			buyerIds.add(userId);
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_006() {
		Logger.start(true, "请求用户中包含首单和非首单用户--获取成功");
		try {
			OrderCallService orderCallService = new OrderCallService();

			int userId = orderCallService.createNewUser();
			TradingServiceResp placeOrder = TradingPlaceOrderCallService.placeOrderWithUserId(userId);
			long tradingId = placeOrder.getTradingId();
			BigDecimal totalPrice = placeOrder.getPayableAmount();
			
			TradingCallService.payOrder(userId, totalPrice, tradingId, false, 2);
			
			int userId2 =  orderCallService.createNewUser();

			List<Integer> buyerIds = new ArrayList<Integer>();
			buyerIds.add(userId);
			buyerIds.add(userId2);
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_007() {
		Logger.start(true, "用户不存在--获取成功, 也属于首单用户");
		try {

			List<Integer> buyerIds = new ArrayList<Integer>();
			buyerIds.add(404);
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_GetBuyerFirstOrderInfo_008() {
		Logger.start(true, "请求不传用户id--获取成功, 没有首单信息");
		try {

			List<Integer> buyerIds = new ArrayList<Integer>();
			req.setBuyerIds(buyerIds);
			call.setData(req);
			call.callService();
			Logger.verifyEquals("400", call.getCode(), "校驗code");

			Logger.verifyEquals("buyerIds:buyerIds未提供", call.getString("msg"),
					"校驗msg");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}